package db_servicer

import "regexp"

// "net"
// "fmt"
// "encoding/gob"
//	"gopkg.in/rana/ora.v3"
//	"ifms/tcp_servicer"

func Outgoing_msg_done(logids string) (int8, string) {
	// logger = log.New(os.Stdout, "Outgoing Msg Done:", log.LstdFlags|log.Lshortfile)

	if _, err := ses.PrepAndExe("CALL pkg_tcp_svr.device_outgoing_done(:p1)",
		logids); err != nil {

		//		logger.Fatal(err)
		logger.Println(err)
	}

	return 0, "Outgoing Table was updated!"

}

// func save_DevConn ( conn net.Conn, device_id string ) {
// 	logger = log.New(os.Stdout, "Save Dev Conn :", log.LstdFlags|log.Lshortfile)

// 	dataFile, err := os.Create(fmt.Sprintf("DevConnList/%v",device_id ))

//  	if err != nil {
//  		logger.Println(err)
//  	}

//  	dataEncoder := gob.NewEncoder(dataFile)

//  	dataEncoder.Encode( conn )

// 	dataFile.Close()
// }

// func load_DevConn ( device_id string ) ( conn net.Conn, err error ){
// 	logger = log.New(os.Stdout, "Load Dev Conn :", log.LstdFlags|log.Lshortfile)

// 	var v_conn net.Conn

// 	dataFile, err := os.Open(fmt.Sprintf("DevConnList/%v",device_id ))

//  	if err != nil {
//  		logger.Println(err)
//  		return  nil, err
//  	}

//  	dataDecoder := gob.NewDecoder(dataFile)
//  	err = dataDecoder.Decode(&v_conn )

//  	if err != nil {
//  		logger.Println(err)
// 	 	return nil, err
//  	}

//  	dataFile.Close()

//  	return v_conn, nil

// }

func Save_incoming_msg(msg Incomeing_msg) (int8, string) {
	var v_err_code int8 = 0

	// 0 : succeed
	// others: fail

	// Write Date that received from GPRS into DB
	// Fetch Download Data from DB and return them to caller so that they can be send back to GPRS devices
	//    return data format : [] string
	// logger = log.New(os.Stdout, "Save Incoming Msg:", log.LstdFlags|log.Lshortfile)

	logger.Print(msg)

	var v_ret string

	if _, err := ses.PrepAndExe("CALL pkg_tcp_svr.incoming_data(:p1,:p2,:p3,:p4,:p5,:p6)",
		msg.Device_id, msg.Data_type, msg.Data_str,
		msg.Remote_IP_Addr, msg.Remote_IP_Port, &v_ret); err != nil {

		//		logger.Fatal(err)
		logger.Print(err)
		return -1, v_ret
	}

	if regexp.MustCompile(`^ORA-[0-9]{1,5}:`).MatchString(v_ret) {
		logger.Print(v_ret)
		v_err_code = -1
	}

	return v_err_code, v_ret

}
